import 'package:flutter/material.dart';
import 'package:gold/base/config.dart';
import 'package:gold/http/api_shop.dart';
import 'package:gold/model/order_model.dart';
import 'package:gold/ui/my/shop/shop_config.dart';
import 'package:gold/utils/res.dart';
import 'package:gold/widgets/http_image.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';
import 'package:gold/base/provider_widget.dart';
import 'package:gold/ui/my/shop/order/shop_order_list_viewmodel.dart';
import 'package:gold/utils/xfg_color.dart';
import 'package:gold/utils/xfg_size.dart';
import 'package:gold/widgets/common_widgets.dart';
import 'package:gold/widgets/xfg_text.dart';

/// @description: 店铺订单列表页面
/// @author tangzhentao
/// @created at 21:32 2024/12/14

class ShopOrderListPage extends StatefulWidget {
  /// 订单状态 [OrderStatus]
  final String orderStatus;

  const ShopOrderListPage({super.key, required this.orderStatus});

  @override
  State<StatefulWidget> createState() => _ShopOrderListState();
}

class _ShopOrderListState extends State<ShopOrderListPage> with AutomaticKeepAliveClientMixin {

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return ProviderWidget<ShopOrderListViewmodel>(
        model: ShopOrderListViewmodel(ApiShop.orderList, widget.orderStatus),
        onInit: (data) => data.firstLoad(),
        builder: (ctx, shopOrder) => SmartRefresher(
          controller: shopOrder.controller,
          enablePullUp: true,
          enablePullDown: true,
          onRefresh: shopOrder.refresh,
          onLoading: shopOrder.loadMore,
          child: ListView.builder(
              itemCount: shopOrder.list.length,
              itemBuilder: (_, index) {
                final model = shopOrder.list[index];
                final address = model.address;
                final orderNo = model.orderNo?? '';
                final productName = model.detail?.product?.name?? '';
                final quantity = model.quantity?.toString()?? '1';
                final createdAt = model.createdAt?? '';
                final isLast = index == shopOrder.list.length - 1;
                return Container(
                  decoration: white10Decoration,
                  margin: EdgeInsets.fromLTRB(XfgSize().size10, XfgSize().size10, XfgSize().size10, isLast ? XfgSize().bottomBarHeight:0),
                  child: Column(
                    children: [
                      Container(
                        height: XfgSize().size49,
                        padding: EdgeInsets.symmetric(horizontal: XfgSize().size12),
                        child: Row(
                          children: [
                            Expanded(child: XfgText('订单号:$orderNo', fontSize: XfgSize().text14, color: XfgColor.text1)),
                            XfgText(getShopOrderStatusDesc(model.status), fontSize: XfgSize().text16, color: model.status == OrderStatus.done || model.status == OrderStatus.cancel ? XfgColor.text3:XfgColor.theme, bold: FontWeight.bold)
                          ],
                        ),
                      ),
                      strokeHeightContainer,
                      Padding(
                        padding: EdgeInsets.fromLTRB(XfgSize().size10, XfgSize().size10, XfgSize().size10, XfgSize().size8),
                        child: SizedBox(
                          height: XfgSize().size84,
                          child: Row(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              HttpImage(model.detail?.product?.coverImage, size: Size.square(XfgSize().size78), radius: BorderRadius.circular(XfgSize().size6)),
                              SizedBox(width: XfgSize().size12),
                              Expanded(
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Row(
                                      children: [
                                        Expanded(child: XfgText(productName, fontSize: XfgSize().text14, color: XfgColor.text1D, height: 1.5, maxLines: 2)),
                                        Container(
                                          width: XfgSize().size34,
                                          alignment: Alignment.centerRight,
                                          child: XfgText('x$quantity', fontSize: XfgSize().text14, color: XfgColor.text1D),
                                        )
                                      ],
                                    ),
                                    SizedBox(height: XfgSize().size8),
                                    XfgText(createdAt, fontSize: XfgSize().text12, color: XfgColor.text3),
                                    SizedBox(height: XfgSize().size8),
                                   _getPriceWidget(model)
                                  ],
                                ),
                              )
                            ],
                          ),
                        ),
                      ),
                      strokeHeightContainer,
                      Padding(
                        padding: EdgeInsets.fromLTRB(XfgSize().size14, XfgSize().size8, XfgSize().size10, XfgSize().size8),
                        child: Row(
                          children: [
                            _getTotalPriceWidget(model),
                            const Spacer(),
                            Visibility(
                              visible: model.status == OrderStatus.sending,
                              child: TextButton(
                                onPressed: () => shopOrder.expressDelivery(index),
                                style: xfgButtonStyle(Size(XfgSize().size97, XfgSize().size32), radius: XfgSize().size32),
                                child: XfgText('去发货', fontSize: XfgSize().text14, color: XfgColor.white, bold: FontWeight.bold),
                              ),
                            )
                          ],
                        ),
                      ),
                      _logisticsWidget(model, shopOrder, index),
                      ...(model.showAddress == true ? [
                        _listItemInfoWidget('收件信息', '${address?.name?? ''}   ${address?.phone?? ''}', XfgSize().size8),
                        _listItemInfoWidget('快递地址', '${address?.address??''} ${address?.houseNumber?? ''}', XfgSize().size14),
                        _listItemInfoWidget('下单时间', model.createdAt?? '--', XfgSize().size14),
                        _listItemInfoWidget('付款时间', model.createdAt?? '--', XfgSize().size14),
                      ]:[]),
                      Visibility(
                        visible: model.status == OrderStatus.sending,
                        child: GestureDetector(
                          onTap: () => shopOrder.changeAddressShow(index),
                          behavior: HitTestBehavior.opaque,
                          child: Container(
                            alignment: Alignment.center,
                            child: Icon(Icons.list, size: XfgSize().size24, color: model.showAddress == true ? XfgColor.theme:XfgColor.text3),
                          ),
                        ),
                      )
                    ],
                  ),
                );
              }
          ),
        )
    );
  }

  @override
  bool get wantKeepAlive => true;

  /// 列表更多信息通用布局
  Widget _listItemInfoWidget(String text, String value, double top) => Container(
    margin: EdgeInsets.fromLTRB(XfgSize().size10, top, XfgSize().size10, 0),
    child: Row(
      children: [
        SizedBox(width: XfgSize().size64, child: XfgText(text, fontSize: XfgSize().text12, color: XfgColor.text3)),
        Expanded(child: XfgText(value, fontSize: XfgSize().text12, color: XfgColor.text1D))
      ],
    ),
  );

  /// 获取价格描述Widget
  Widget _getPriceWidget(OrderModel model) {
    final price = model.detail?.product?.price ?? 0;
    final points = model.detail?.product?.pointsPrice?? 0;
    final freight = model.freight?? 0;
    final List<InlineSpan> children = [];
    if (price > 0) {
      children.add(TextSpan(text: price.toStringAsFixed(2), style: TextStyle(fontSize: XfgSize().text20)));
    }
    if (points > 0) {
      if (children.isNotEmpty) children.add(TextSpan(text: ' + ', style: TextStyle(fontSize: XfgSize().text16)));
      children.add(TextSpan(text: '$points积分', style: TextStyle(fontSize: XfgSize().text16)));
    }
    if (freight > 0) {
      if (children.isNotEmpty) children.add(WidgetSpan(child: SizedBox(width: XfgSize().size10)));
      children.addAll([
        TextSpan(text: '运费：¥', style: TextStyle(fontSize: XfgSize().text14)),
        TextSpan(text: freight.toStringAsFixed(2), style: TextStyle(fontSize: XfgSize().text20))
      ]);
    }
    return XfgText(price > 0 ? '¥':'', fontSize: XfgSize().text12, color: XfgColor.text1D, children: children);
  }

  /// 获取总价格描述Widget
  Widget _getTotalPriceWidget(OrderModel model) {
    final price = (model.detail?.product?.price ?? 0) * (model.quantity?? 1) + (model.freight?? 0);
    final points = (model.detail?.product?.pointsPrice?? 0) * (model.quantity ?? 1);
    final List<TextSpan> children = [];
    if (price > 0) {
      children.addAll([
        TextSpan(text: ' ¥', style: TextStyle(fontSize: XfgSize().text12)),
        TextSpan(text: price.toStringAsFixed(2), style: TextStyle(fontSize: XfgSize().text20, color: XfgColor.theme))
      ]);
    }
    if (points > 0) {
      if (children.isNotEmpty) children.add(TextSpan(text: ' + ', style: TextStyle(fontSize: XfgSize().text16, color: XfgColor.text1D)));
      children.add(TextSpan(text: '$points积分', style: TextStyle(fontSize: XfgSize().text16, color: XfgColor.theme)));
    }
    return XfgText('合计:', fontSize: XfgSize().text16, color: XfgColor.text3, children: children);
  }

  /// 物流信息Widget
  Widget _logisticsWidget(OrderModel model, ShopOrderListViewmodel viewModel, int index) {
    if (model.status == OrderStatus.receiving) {
      String expressDes = model.express?.expressDetail?.expTextName?? '';
      final expressStatus = getExpressStatusDesc(model.express?.expressDetail?.status);
      final list = model.express?.expressDetail?.data;
      if (list?.isNotEmpty == true) {
        expressDes = '$expressDes：${list?.isNotEmpty == true ? list!.first.context?? '':''}';
      }
      return GestureDetector(
        onTap: () => viewModel.checkLogistics(index),
        behavior: HitTestBehavior.opaque,
        child: Container(
          margin: EdgeInsets.fromLTRB(XfgSize().size5, XfgSize().size8, XfgSize().size10, XfgSize().size5),
          padding: EdgeInsets.only(left: XfgSize().size10, right: XfgSize().size8),
          height: XfgSize().size28,
          decoration: BoxDecoration(color: XfgColor.background, borderRadius: BorderRadius.circular(XfgSize().size2)),
          child: Row(
            children: [
              Image.asset(Res.imagesOrderLogistics, width: XfgSize().size20, height: XfgSize().size15 + XfgSize().size0_5),
              XfgText(' $expressStatus ', fontSize: XfgSize().text12, color: XfgColor.orderLogistics),
              Expanded(child: XfgText(expressDes, fontSize: XfgSize().text12, color: XfgColor.color4F, maxLines: 1, overflow: TextOverflow.ellipsis))
            ],
          ),
        ),
      );
    }

    return SizedBox(height: XfgSize().size10);
  }
}
